package com.yilin.tms.user.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.technical.GoodsConfigure;
import com.yilin.tms.core.entity.user.technical.LineConfigure;
import com.yilin.tms.user.mapper.GoodsConfigureMapper;
import com.yilin.tms.user.mapper.LineConfigureMapper;
import com.yilin.tms.user.service.ILineConfigureService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LineConfigureService extends ServiceImpl<LineConfigureMapper, LineConfigure> implements ILineConfigureService {

    @Resource
    LineConfigureMapper lineConfigureMapper;
    @Resource
    GoodsConfigureMapper goodsConfigureMapper;

    @Override
    public LineConfigure getLineConfigureById(String id) {
        QueryWrapper<LineConfigure> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        LineConfigure lineConfigure = lineConfigureMapper.selectOne(queryWrapper);
        QueryWrapper<GoodsConfigure> queryWrapper2 = new QueryWrapper<>();
        queryWrapper.eq("id", lineConfigure.getId());
        lineConfigure.setGoodsConfigures(goodsConfigureMapper.selectList(queryWrapper2));
        return lineConfigure;
    }

    @Override
    public PageData<LineConfigure> getLineConfigurePage(Account loginUser, LineConfigure query, Integer page, Integer limit) {
        QueryWrapper<LineConfigure> queryWrapper = new QueryWrapper<>();
        QueryUtil.andQueryWrapper(queryWrapper, query);
        return lineConfigureMapper.selectPage(new PageData<>(page, limit), queryWrapper);
    }

    @Override
    public void saveOrUpdateLineConfigure(LineConfigure lineConfigure) {
        //变更规则
        if (lineConfigure.getId() == null) {
            String code = UUID.randomUUID().toString().replace("-", "").substring(0, 4).toUpperCase();
            lineConfigure.setLineCode(code);
            lineConfigureMapper.insert(lineConfigure);
            for (GoodsConfigure goodsConfigure : lineConfigure.getGoodsConfigures()) {
                goodsConfigure.setLineId(lineConfigure.getId());
                goodsConfigureMapper.updateById(goodsConfigure);
            }

        }
        else lineConfigureMapper.updateById(lineConfigure);

    }
}
